package com.huawei.hgip.paintgame.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.huawei.hgip.paintgame.R;
import com.huawei.hgip.paintgame.app.ZZYYActivity;
import com.huawei.hgip.paintgame.m.data.UserProfile;
import com.huawei.hgip.paintgame.util.PGUtil;
import com.huawei.hgip.paintgame.util.VoteT;
import com.huawei.hgip.paintgame.widget.ColorPickerDialog;
import com.huawei.hgip.paintgame.widget.PaintSearchView;

/**
 * 在画图板基础上添加画图搜索相关
 * 
 * @author Administrator
 * 
 */
public class PaintSearchActivity extends ZZYYActivity implements
		ColorPickerDialog.OnColorChangedListener {

	private boolean isFinish = false;
	public int loopCount = 0;
	// private long durTime = 0;
	public long lastTime = 0;// 控制绘画停止时间；
	public String file1 = null;
	public boolean file1ok = false;
	public String file2 = null;
	public boolean file2ok = false;
	public int myPORT = 9999;
	public boolean startDraw = false;// 控制开始监听绘画的线程；
	public int currentService = PGUtil.BC_PIC_SEARCH;// 默认的服务类型
	public int exceptionBackType = 0;

	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// System.out.println("---in handleMessage case 1, thread id is: "
				// + Thread.currentThread().getId());
				whenFinish();
				isFinish = true;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		mc = this;
		// mButton = (Button) findViewById(R.id.Button01);
		// mEditText1 = (EditText) findViewById(R.id.EditText01);
		// mEditText2 = (EditText) findViewById(R.id.EditText02);
		// try {
		// // username = new BufferedReader(new InputStreamReader(
		// // this.getResources().openRawResource(R.raw.nickname))).readLine();
		// nameFile = new File(NAME_FILE);
		// if (!nameFile.exists()) {
		// System.out.println("in namefile not exist!"
		// + nameFile.getPath());
		// File dir = new File("/sdcard/paintgame");
		// if (!dir.exists()) {// 路径不存在
		// if (dir.mkdirs()) {// 创建路径
		// System.out.println("mkdirs ok!");
		// }
		// ;
		// }
		// if (nameFile.createNewFile()) {// 创建文件
		// System.out.println("mk name file ok!");
		// }
		// ;
		// }
		// BufferedReader tmpReader = new BufferedReader(
		// new InputStreamReader(new FileInputStream(nameFile)));
		// username = tmpReader.readLine();
		// tmpReader.close();
		// System.out.println("username is: " + username);
		// mEditText2.setText(username);
		// } catch (NotFoundException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		int screenWidth,screenHeight;
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		screenWidth = display.getWidth();
		screenHeight = display.getHeight();

		mbmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
		mbmap.eraseColor(Color.BLACK);
		// create layout and views
		layout = new RelativeLayout(this);
		// mView's layout rule
		RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);

		// resetButton1's layout rule
		RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
		lp2.addRule(RelativeLayout.ALIGN_RIGHT, MVIEW_ID);

		// resetButton2's layout rule
//		RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(
//				ViewGroup.LayoutParams.WRAP_CONTENT,
//				ViewGroup.LayoutParams.WRAP_CONTENT);
//		lp3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
//		lp3.addRule(RelativeLayout.LEFT_OF, IMAGEBUTTON1_ID);

		// resetButton3's layout rule
		RelativeLayout.LayoutParams lp4 = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		lp4.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
		lp4.addRule(RelativeLayout.LEFT_OF, IMAGEBUTTON1_ID);

		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setColor(Color.WHITE);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(3);
		//对于height分辨率达到800以上的，画笔加粗
		if(screenHeight > 799){
			mPaint.setStrokeWidth(4);			
		}else{
			mPaint.setStrokeWidth(3);	
		}
		mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);

		mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);

		mView = new PaintSearchView(this, mbmap, mPaint);
		mView.setId(MVIEW_ID);

		resetButton1 = new ImageButton(this);
		resetButton1.setId(IMAGEBUTTON1_ID);
		resetButton1.setImageResource(R.drawable.vbad);
		resetButton1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new VoteT(PGUtil.VOTE_BAD, votePicName);
				mbmap.eraseColor(Color.BLACK);
				setIsFinish(false);
				setButtonsVisible(View.INVISIBLE);
				mView.invalidate();

			}
		});

//		resetButton2 = new ImageButton(this);
//		resetButton2.setId(IMAGEBUTTON2_ID);
//		resetButton2.setImageResource(R.drawable.vmiddle);
//		resetButton2.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				new VoteT(PGUtil.VOTE_MIDDLE, username + " : " + votePic);
//				mbmap.eraseColor(Color.BLACK);
//				setIsFinish(false);
//				setButtonsVisible(View.INVISIBLE);
//				mView.invalidate();
//
//			}
//		});

		resetButton3 = new ImageButton(this);
		resetButton3.setId(IMAGEBUTTON3_ID);
		resetButton3.setImageResource(R.drawable.vgood);
		resetButton3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new VoteT(PGUtil.VOTE_GOOD, votePicName);
				mbmap.eraseColor(Color.BLACK);
				setIsFinish(false);
				setButtonsVisible(View.INVISIBLE);
				mView.invalidate();
			}
		});
		// resetButton1.setAlpha(50);
		setButtonsVisible(View.INVISIBLE);

		layout.addView(mView, lp1);
		layout.addView(resetButton1, lp2);
		//layout.addView(resetButton2, lp3);
		layout.addView(resetButton3, lp4);

		beginPop = Toast.makeText(this, "放松。。。画画。。。", Toast.LENGTH_LONG);
		// mButton.setOnClickListener(new OnClickListener() {
		// public void onClick(View v) {
		// mView.myHOST = mEditText1.getText().toString();
		// String newName = mEditText2.getText().toString();
		//String newName = "testuser";
		setContentView(layout);
		beginPop.show();

		// System.out.println("newName is: " + newName);
		// if (!newName.equals(username)) {
		// username = newName;
		// try {
		// BufferedWriter tmpWriter = new BufferedWriter(
		// new OutputStreamWriter(new FileOutputStream(
		// nameFile)));
		// tmpWriter.write(username);
		// tmpWriter.flush();
		// tmpWriter.close();
		// } catch (FileNotFoundException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }

		// }
		// });
	}

	private Paint mPaint;
	private MaskFilter mEmboss;
	private MaskFilter mBlur;
	private Bitmap mbmap;
	//private Button mButton;
	// private EditText mEditText1;
	//private EditText mEditText2;
	Toast beginPop;
	public static int userid = PGUtil.getUserID();
	static final String NAME_FILE = "/sdcard/paintgame/nickname.dat";
	static final int MVIEW_ID = 1;
	static final int IMAGEBUTTON1_ID = 2;
	//static final int IMAGEBUTTON2_ID = 3;
	static final int IMAGEBUTTON3_ID = 4;
	public String votePicName;
	File nameFile;
	Context mc;
	// private static final String HOST = "10.138.19.43";
	// private String HOST = "10.138.20.58";
	// private static final String HOST = "10.70.110.130";
	//private Socket socket = null;
	public PaintSearchView mView;
	private ImageButton resetButton1;
	//private ImageButton resetButton2;
	private ImageButton resetButton3;
	private RelativeLayout layout;

	public void colorChanged(int color) {
		mPaint.setColor(color);
	}

	private static final int COLOR_MENU_ID = Menu.FIRST;
	private static final int EMBOSS_MENU_ID = Menu.FIRST + 1;
	private static final int BLUR_MENU_ID = Menu.FIRST + 2;
	private static final int ERASE_MENU_ID = Menu.FIRST + 3;
	private static final int PIC_SER_MENU_ID = Menu.FIRST + 4;
	private static final int DRAW_SER_MENU_ID = Menu.FIRST + 5;

	// private static final int SAVE_MENU_ID = Menu.FIRST + 5;
	// private static final int SEND_MENU_ID = Menu.FIRST + 6;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
		menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
		menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
		menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('6', 'z');
		// menu.add(0, PIC_SER_MENU_ID, 0, "findPic").setShortcut('7', 'z');
		// menu.add(0, DRAW_SER_MENU_ID, 0, "findDraw").setShortcut('8', 'z');
		// menu.add(0, SAVE_MENU_ID, 0, "Save").setShortcut('5', 'z');
		// menu.add(0, SEND_MENU_ID, 0, "Send").setShortcut('5', 's');
		// menu.add(0, SRCATOP_MENU_ID, 0, "Send").setShortcut('5', 's');

		/****
		 * Is this the mechanism to extend with filter effects? Intent intent =
		 * new Intent(null, getIntent().getData());
		 * intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
		 * menu.addIntentOptions( Menu.ALTERNATIVE, 0, new ComponentName(this,
		 * NotesList.class), null, intent, 0, null);
		 *****/
		return true;
	}

	// @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	// @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		mPaint.setXfermode(null);
		mPaint.setAlpha(0xFF);

		switch (item.getItemId()) {
		case COLOR_MENU_ID:
			new ColorPickerDialog(this, this, mPaint.getColor()).show();
			return true;
		case EMBOSS_MENU_ID:
			if (mPaint.getMaskFilter() != mEmboss) {
				mPaint.setMaskFilter(mEmboss);
			} else {
				mPaint.setMaskFilter(null);
			}
			return true;
		case BLUR_MENU_ID:
			if (mPaint.getMaskFilter() != mBlur) {
				mPaint.setMaskFilter(mBlur);
			} else {
				mPaint.setMaskFilter(null);
			}
			return true;
		case ERASE_MENU_ID:
			mbmap.eraseColor(Color.BLACK);
			setIsFinish(false);
			setButtonsVisible(View.INVISIBLE);
			mView.invalidate();
			// mPaint.setXfermode(new
			// PorterDuffXfermode(PorterDuff.Mode.CLEAR));
			return true;
		case PIC_SER_MENU_ID:
			currentService = PGUtil.BC_PIC_SEARCH;
			return true;

		case DRAW_SER_MENU_ID:
//			currentService = PGUtil.DRAW_SEARCH;
//			return true;
			// case SRCATOP_MENU_ID:
			// setContentView(new ResultView(this,
			// BitmapFactory.decodeFile(filepath), mPaint))
			// mPaint.setXfermode(new
			// PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
			// mPaint.setAlpha(0x80);
			// return true;
			// case SAVE_MENU_ID:
			// return true;
			// case SEND_MENU_ID:
			// return true;
		}
		return super.onOptionsItemSelected(item);
	}


	// 网上抄来的，将字节转成 int。b 长度不得小于 4，且只会取前 4 位。
//	public static int b2i(byte[] b) {
//		int value = 0;
//		for (int i = 0; i < 4; i++) {
//			int shift = (4 - 1 - i) * 8;
//			value += (b[i] & 0x000000FF) << shift;
//		}
//		return value;
//	}

	public void setButtonsVisible(int visibleFlag) {
		resetButton1.setVisibility(visibleFlag);
		//resetButton2.setVisibility(visibleFlag);
		resetButton3.setVisibility(visibleFlag);
	}

	//@Override
//	public void onAnimationEnd(Animation animation) {
//		// 展示第一张图
//		if (file1ok && file2ok) {
//			// System.out.println("in listener file1ok");
//			mView.setBitMap(BitmapFactory.decodeFile(file1));
//			// System.out.println("mAnimation2.setBitMap");
//			Animation tmpAnim = AnimationUtils.loadAnimation(this,
//					R.anim.myanimation2);
//			mView.setAnimation(tmpAnim);
//			tmpAnim.setAnimationListener(this);
//			// System.out.println("mAnimation2 2");
//			mView.invalidate();
//			// System.out.println("mAnimation2 end");
//			file1 = null;
//			file1ok = false;
//			return;
//
//		} else if (file2ok) {// 展示第二张图
//			if (file2 == null) {// 完成了第二张图展示
//				file2ok = false;
//				loopCount = 0;// 循环等待清零
//				// //增加reset 按钮
//				setButtonsVisible(View.VISIBLE);
//				return;
//			}
//			// System.out.println("in listener file2ok 1");
//			mView.setBitMap(BitmapFactory.decodeFile(file2));
//			// System.out.println("mAnimation3.setBitMap");
//			Animation tmpAnim = AnimationUtils.loadAnimation(this,
//					R.anim.myanimation3);
//			mView.setAnimation(tmpAnim);
//			tmpAnim.setAnimationListener(this);
//			String text = new File(file2).getName();
//			votePic = text;// get current vote pic name
//			if (currentService == PGUtil.DRAW_SEARCH) {
//				Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
//			}
//			mView.invalidate();
//			file2 = null;
//
//			return;
//		} else {// 循环等待
//			loopCount++;
//			// 循环10次则退出
//			if (loopCount > 12) {
//				loopCount = 0;
//				return;
//			}
//			// 判断失败的返回
//			if (exceptionBackType == PGUtil.SERVER_ERR) {
//				String text = "系统暂停服务，请稍候再试。。。";
//				Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
//				loopCount = 0;
//				return;
//			} else if (exceptionBackType == PGUtil.NO_SUIT_RESULT) {
//				String text = "没有找到合适的结果，请重画一个试试看。。。";
//				Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
//				loopCount = 0;
//				return;
//			}
//			exceptionBackType = 0;// 初始化失败返回标志位
//
//			Animation tmpAnim = AnimationUtils.loadAnimation(this,
//					R.anim.myanimation2);
//			mView.setAnimation(tmpAnim);
//			tmpAnim.setAnimationListener(this);
//			// System.out.println("mAnimation0 2");
//			mView.invalidate();
//			return;
//		}
//
//	}
//
//	//@Override
//	public void onAnimationRepeat(Animation animation) {
//		// TODO Auto-generated method stub
//
//	}
//
//	//@Override
//	public void onAnimationStart(Animation animation) {
//		// TODO Auto-generated method stub
//
//	}

	public void whenFinish() {
		// System.out.println("in whenFinish");
		startDraw = false;
		// System.out.println("whenFinish step0");
		Animation mAnimation1 = AnimationUtils.loadAnimation(this,
				R.anim.alphanim);
		// System.out.println("whenFinish step1");
		mView.setAnimation(mAnimation1);
		// System.out.println("whenFinish step2");
		mAnimation1.setAnimationListener(mView);
		// System.out.println("whenFinish step3");
		mView.invalidate();
		// System.out.println("whenFinish over");
	}

	public void setIsFinish(boolean isFinis) {
		isFinish = isFinis;
	}
	
	public boolean isFinish() {
		return isFinish;
	}

	public void popupException(String popupContent){
		super.popupException(popupContent);
	}

}
